package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.IdCardUtil;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 入住Service业务层处理
 * 
 * @author ZHD
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //老人家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        //签约办理
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        //入住配置
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        //获取 身份证号
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        //获取 身份证号
        String idCardNo = checkInElderDto.getIdCardNo();
        //获取 床位ID
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        //1.校验老人是否已入住
        checkInElder(idCardNo);
        //2.更新床位状态
        Bed bed = bedMapper.selectBedById(bedId);
        bed.setBedStatus(1);
//        LambdaQueryWrapper<Bed> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Bed::getId, bedId)
//                .eq(Bed::getBedStatus, 0);
//        int row = bedMapper.update(bed, queryWrapper);
        int row=bedMapper.updateEnableStatusById(bed.getBedStatus(),bedId);
        if (row <= 0){
            throw new BaseException("已有老人入住，修改床位状态失败");
        }
        //3.新增或更新老人
        Elder elder = insertOrUpdateElder(checkInElderDto, bed);
        //4.新增签约信息
        inertContract(elder,checkInConfigDto,checkInContractDto);
        //5.新增入住信息
        CheckIn checkIn = insertElderCheckIn(elder, checkInConfigDto, elderFamilyDtoList);
        //6.新增入住配置
        insertCheckInConfig(checkIn, checkInConfigDto);
    }

    /**
     * 查询入住详情
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInDetailVo(Long id) {
        //1.根据id查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //2.根据老人身份证
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        String idCardNo = elder.getIdCardNo();
        //获取出生日期
        String birthDate = IdCardUtil.getBirthDate(idCardNo);
        LocalDate birthday = LocalDate.parse(birthDate);
        int age = Period.between(birthday, LocalDate.now()).getYears();
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder,checkInElderVo);
        //3.根据老人id查询合同
        Contract contract = contractMapper.selectContractByElderId(elderId);
        //4.根据入住id查询入住配置
        CheckInConfig checkInConfig=checkInConfigMapper.selectCheckInConfigByCheckInId(id);
        if (Objects.isNull(checkInConfig)){
            throw new BaseException("未查询到入住配置");
        }
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
//        checkInConfigVo.setCreateBy(checkInConfig.getCreateBy());
//        checkInConfigVo.setCreateTime(checkInConfig.getCreateTime());
//        checkInConfigVo.setUpdateBy(checkInConfig.getUpdateBy());
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        //5.根据入住信息获取家属信息
        List<ElderFamilyVo> elderFamilyVoList= checkIn.getRemark() == null ?
                new ArrayList<>() : JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        //6.封装
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     * @param checkIn
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInConfigDto
     * @param elderFamilyDtoList
     */
    private CheckIn insertElderCheckIn(Elder elder, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(elder,checkIn,"id");
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约信息
     * @param elder
     * @param checkInConfigDto
     * @param checkInContractDto
     */

    private void inertContract(Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     * @param checkInElderDto
     * @param bed
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        //准备老人基本数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elderDb = elderMapper.selectOne(queryWrapper);
        if(Objects.isNull(elderDb)){
            //新增
            elderMapper.insert(elder);
        } else{
            //更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }


    /**
     * 检测老人是否已入住
     * @param idCardNo 老人身份证号
     */
    private void checkInElder(String idCardNo) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, idCardNo)
                 .in(Elder::getStatus, 1, 2, 4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        //1.1老人已入住
        if (!Objects.isNull(elder)){
            throw new BaseException("老人已入住");
        }
    }
}
